package com.studyroom.controller;

import cn.hutool.http.HttpResponse;
import com.studyroom.dto.ChatMessage;
import com.studyroom.dto.Result;
import com.studyroom.entity.ChatFile;
import com.studyroom.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/chat")
public class ChatController {
    @Autowired
    private ChatService chatService;
    @RequestMapping("/receiveSolo")
    public Result receiveSolo(@RequestParam Long id){
        return chatService.receiveSolo(id);
    }
    @PostMapping("/sendSolo")
    public Result sendSolo(@RequestBody ChatMessage chatMessage){
        return chatService.sendSole (chatMessage);
    }
    @RequestMapping("/uploadFile")
    public Result uploadFile(@RequestParam("file")MultipartFile file,@RequestParam Long sender,@RequestParam Long recever){
        log.info ("message -->{},{},{},{}",file.getName (),file.getOriginalFilename (),sender,recever);
        return chatService.uploadFile (file,sender,recever);
    }
    @GetMapping("/downloadFile")
    public void downloadFile(HttpServletResponse response,@RequestParam Long fileId){
        log.info ("fileId -> {}",fileId);
        try{
            ChatFile chatFile = chatService.downloadFile (fileId);
            if(chatFile==null){
                return;
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");
            response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(chatFile.getName (), "UTF-8"));
            response.setHeader ("filename",chatFile.getName ());
            OutputStream outputStream = response.getOutputStream ();
            outputStream.write (chatFile.getData ());
            outputStream.close ();
        }catch (Exception e){
            e.printStackTrace ();
        }
    }
}
